package org.tea.springdata.web.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays;

import javax.servlet.http.HttpServletResponse;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.tea.springdata.web.Constants;
import org.tea.springdata.web.utils.CAUtils;
import org.tea.springdata.web.utils.HttpClientUtils;

import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;

/**
 * @author: John zhang
 * @version: 0.1
 */
@Controller
@RequestMapping("/jc/weixin")
public class WeixinController {
	
	/**
	 * 令牌有效时间
	 */
	private int accessTokenExpires;
	/**
	 * 获取令牌时的时间
	 */
	private long getAccessTokenTime;
	
	private String accessToken;
	
	@RequestMapping("/checkSignature")
	public void checkSignature ( HttpServletResponse resp, String signature, String timestamp, String nonce, String echostr ) {
		String[] sortArray = new String[] { Constants.TOKEN, timestamp, nonce };
		Arrays.sort ( sortArray );
		String mergeStr = sortArray[0] + sortArray[1] + sortArray[2];
		String encodeData = CAUtils.toHexString ( CAUtils.encodeSHA1 ( mergeStr.getBytes () ) );
		if ( signature.equals ( encodeData ) ) {
			try {
				OutputStream out = resp.getOutputStream ();
				out.write ( echostr.getBytes () );
				out.flush ();
			} catch ( IOException e ) {
				e.printStackTrace();
			} 
		}
	}
	
	public String getAccessToken () throws Exception {
		if ( System.currentTimeMillis () - getAccessTokenTime < accessTokenExpires ) {
			return accessToken;
		}
		String url = String.format ( "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s", Constants.APPID, Constants.APPSECRET );
		HttpGet request = new HttpGet ( url );
		HttpResponse resp = HttpClientUtils.getHttpClient ().execute ( request );
		if ( resp.getStatusLine ().getStatusCode () == org.apache.http.HttpStatus.SC_OK ) {
			String result = EntityUtils.toString ( resp.getEntity () );
			JsonParser jp = new JsonFactory ().createParser ( result );
			while ( jp.nextToken () != JsonToken.END_OBJECT ) {
				String fieldName = jp.getCurrentName ();
				if ( fieldName.equals ( "access_token" ) ) {
					accessToken = jp.getText ();
				} else if ( fieldName.equals ( "expires_in" ) ) {
					accessTokenExpires = Integer.parseInt ( jp.getText () ) * 1000;
				}
			}
			getAccessTokenTime = System.currentTimeMillis ();
			return accessToken;
		}
		return null;
	}
	
}
